package reggie.ruiji.filter;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import reggie.ruiji.common.R;
import reggie.ruiji.untils.JwtUtils;

import java.io.IOException;
/*
    登录效验
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class demofilter implements Filter
{
    //路径匹配器，支持通配符
    public static final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest URL=(HttpServletRequest) servletRequest;
        HttpServletResponse res=(HttpServletResponse) servletResponse;

        //1.获取URL的string类型
        String url=URL.getRequestURI().toString();
        log.info("拦截到请求");
        String []urls=new String[]{
                  "/employee/login",
                  "/employee/logout",
                  "/backend/**",
                  "/front/**",
                  "/common/**",
                  "/user/sendMsg",
                  "/user/login"

        };//定义不需要处理的请求路径

        //2.判断本次请求是否需要处理
        boolean check=cheak(urls,url);//判断本次请求是否需要处理

        //3.如果是登录请求，则不需要处理，直接放行
       if(check)
       {
           filterChain.doFilter(servletRequest, servletResponse);
           log.info("登录请求，放行");
           return ;
       }

        //4-1.判断登录状态，如果已经登录，则直接放行
       if(URL.getSession().getAttribute("employee")!=null)
       {
           filterChain.doFilter(servletRequest, servletResponse);
           log.info("已经登录，放行");
           return ;
       }
        //4-2.判断登录状态，如果已经登录，则直接放行
        if(URL.getSession().getAttribute("user")!=null)
        {
            filterChain.doFilter(servletRequest, servletResponse);
            log.info("已经登录，放行");
            return ;
        }


        //5.如果未登录则返回登录结果
            log.info("未登录");
            res.getWriter().write(JSONObject.toJSONString(R.error("NOTLOGIN")));//此处需要导包
            return ;



    }

    public boolean cheak(String[]urls,String requestURL)
    {
            for(int i=0;i<urls.length;i++)
            {
                if(pathMatcher.match(urls[i],requestURL))
                {
                    return true;
                }
            }
            return false;
    }
}
